<template>
  <div class="page-container">
    <!-- 顶部导航栏 -->
    <TopNav />

    <!-- 操作按钮区域 - 优化布局 -->
    <div class="action-bar">
      <el-row :gutter="15" align="middle">
        <!-- 搜索框 - 占据主要空间 -->
        <el-col :span="8">
          <el-input
            v-model="searchName"
            placeholder="请输入被反映人姓名"
            clearable
            style="width: 100%;"
            size="large"
          />
        </el-col>
        
        <!-- 按钮组 - 紧凑排列 -->
        <el-col :span="16" class="button-group">
          <el-button 
            type="info" 
            size="large" 
            icon="Search" 
            @click="handleSearch"
          >
            查询
          </el-button>

           <el-button 
            type="primary" 
            size="large" 
            icon="Download" 
            @click="showImportDialog"
          >
            导入
          </el-button>
          
          <el-button 
            type="success" 
            size="large" 
            icon="Plus" 
            @click="showAddDialog"
          >
            新增
          </el-button>

           <el-button 
            type="warning" 
            size="large" 
            icon="Upload" 
            @click="exportData"
          >
            导出
          </el-button>
        </el-col>
      </el-row>
    </div>

    <div class="card-container">
      <div class="table-wrapper">
        <el-table :data="problemCluesList" border class="full-height-table"
            :header-cell-style="{ background: '#f0f0f0' }">
          <el-table-column prop="report_unit_name" label="填报单位名称" align="center" width="150"></el-table-column>
          <el-table-column prop="report_unit_code" label="填报单位代码" align="center" width="150"></el-table-column>
          <el-table-column prop="reflected_person" label="被反映人" align="center" width="120"></el-table-column>
          <el-table-column prop="work_unit_and_position" label="工作单位及职务" align="center" width="200"></el-table-column>
          <el-table-column prop="rank" label="职级" align="center" width="100"></el-table-column>
          <el-table-column prop="handling_agency" label="办理机关" align="center" width="150"></el-table-column>
          <el-table-column prop="main_problem_clue" label="主要问题线索" align="center" width="200"></el-table-column>
          <el-table-column prop="accept_clue_code" label="受理线索编码" align="center" width="150"></el-table-column>
           <el-table-column prop="accept_person_code" label="受理人员编码" align="center" width="150"></el-table-column>
          <el-table-column prop="accept_time" label="受理时间" align="center" width="150"></el-table-column>
          <el-table-column prop="handling_time" label="办理时间" align="center" width="150"></el-table-column>
          <el-table-column label="操作" align="center" fixed="right">
            <template #default="scope">
              <el-button 
                size="small" 
                :icon="Edit" 
                @click="handleEdit(scope.row)" 
              />
              <el-button 
                size="small" 
                :icon="Delete" 
                @click="handleDelete(scope.row.id)" 
              />
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页组件 -->
        <div class="pagination-container">
          <el-pagination
            v-model:current-page="pagination.currentPage"
            v-model:page-size="pagination.pageSize"
            :page-sizes="[10, 20, 50, 100]"
            :total="pagination.total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>

      </div>
    </div>

    
    <!-- 新增/编辑对话框 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="80%" top="5vh">
      <el-form :model="form" :rules="rules" ref="formRef" label-width="140px">
        <el-row :gutter="20">
          <!-- 第一列 -->
          <el-col :span="6">
            <el-divider content-position="left">基本信息</el-divider>
            <el-form-item label="主件标识" prop="main_mark">
              <el-input v-model="form.main_mark" placeholder="请输入主件标识" />
            </el-form-item>
            <el-form-item label="是否单位" prop="is_unit">
              <el-select v-model="form.is_unit" placeholder="请选择">
                <el-option label="是" value="是" />
                <el-option label="否" value="否" />
              </el-select>
            </el-form-item>
            <el-form-item label="填报单位名称" prop="report_unit_name">
              <el-input v-model="form.report_unit_name" placeholder="请输入填报单位名称" />
            </el-form-item>
            <el-form-item label="填报单位代码" prop="report_unit_code">
              <el-input v-model="form.report_unit_code" placeholder="请输入填报单位代码" />
            </el-form-item>
            <el-form-item label="被反映人" prop="reflected_person">
              <el-input v-model="form.reflected_person" placeholder="请输入被反映人" />
            </el-form-item>
            <el-form-item label="工作单位及职务" prop="work_unit_and_position">
              <el-input v-model="form.work_unit_and_position" placeholder="请输入工作单位及职务" />
            </el-form-item>
            <el-form-item label="职级" prop="rank">
              <el-input v-model="form.rank" placeholder="请输入职级" />
            </el-form-item>
            <el-form-item label="办理机关" prop="handling_agency">
              <el-input v-model="form.handling_agency" placeholder="请输入办理机关" />
            </el-form-item>
            <el-form-item label="主要问题线索" prop="main_problem_clue">
              <el-input v-model="form.main_problem_clue" placeholder="请输入主要问题线索" type="textarea" :rows="2" />
            </el-form-item>
            <el-form-item label="信访编码" prop="petition_code">
              <el-input v-model="form.petition_code" placeholder="请输入信访编码" />
            </el-form-item>

            <el-divider content-position="left">受理信息</el-divider>
            <el-form-item label="受理线索编码" prop="accept_clue_code">
              <el-input v-model="form.accept_clue_code" placeholder="请输入受理线索编码" />
            </el-form-item>
            <el-form-item label="受理人员编码" prop="accept_person_code">
              <el-input v-model="form.accept_person_code" placeholder="请输入受理人员编码" />
            </el-form-item>
            <el-form-item label="处置线索编码" prop="disposal_clue_code">
              <el-input v-model="form.disposal_clue_code" placeholder="请输入处置线索编码" />
            </el-form-item>
            <el-form-item label="处置人员编码" prop="disposal_person_code">
              <el-input v-model="form.disposal_person_code" placeholder="请输入处置人员编码" />
            </el-form-item>
          </el-col>
          
          <!-- 第二列 -->
          <el-col :span="6">
            <el-divider content-position="left">对象信息</el-divider>
            <el-form-item label="是否国家监察对象" prop="is_national_supervision_object">
              <el-select v-model="form.is_national_supervision_object" placeholder="请选择">
                <el-option label="是" value="是" />
                <el-option label="否" value="否" />
              </el-select>
            </el-form-item>
            <el-form-item label="挽回经济损失（万元）" prop="recover_economic_loss">
              <el-input v-model="form.recover_economic_loss" placeholder="请输入金额" type="number" />
            </el-form-item>
            <el-form-item label="收缴金额（万元）" prop="recovery_amount">
              <el-input v-model="form.recovery_amount" placeholder="请输入金额" type="number" />
            </el-form-item>
            <el-form-item label="没收金额" prop="confiscation_amount">
              <el-input v-model="form.confiscation_amount" placeholder="请输入金额" type="number" />
            </el-form-item>
            <el-form-item label="责令退赔金额" prop="order_refund_amount">
              <el-input v-model="form.order_refund_amount" placeholder="请输入金额" type="number" />
            </el-form-item>
            <el-form-item label="追缴失职渎职滥用职权造成的损失金额" prop="recover_loss_due_to_misconduct">
              <el-input v-model="form.recover_loss_due_to_misconduct" placeholder="请输入金额" type="number" />
            </el-form-item>
            <el-form-item label="登记上交金额" prop="register_submit_amount">
              <el-input v-model="form.register_submit_amount" placeholder="请输入金额" type="number" />
            </el-form-item>

            <el-divider content-position="left">个人信息</el-divider>
            <el-form-item label="民族" prop="ethnicity">
              <el-input v-model="form.ethnicity" placeholder="请输入民族" />
            </el-form-item>
            <el-form-item label="出生年月" prop="birth_date">
              <el-date-picker v-model="form.birth_date" type="date" placeholder="选择出生年月" />
            </el-form-item>
            <el-form-item label="人大代表" prop="npc_member">
              <el-select v-model="form.npc_member" placeholder="请选择">
                <el-option label="是" value="是" />
                <el-option label="否" value="否" />
              </el-select>
            </el-form-item>
            <el-form-item label="政协委员" prop="cppcc_member">
              <el-select v-model="form.cppcc_member" placeholder="请选择">
                <el-option label="是" value="是" />
                <el-option label="否" value="否" />
              </el-select>
            </el-form-item>
            <el-form-item label="是否纪检监察干部" prop="is_discipline_inspection_official">
              <el-select v-model="form.is_discipline_inspection_official" placeholder="请选择">
                <el-option label="是" value="是" />
                <el-option label="否" value="否" />
              </el-select>
            </el-form-item>
            <el-form-item label="处置情况报告" prop="disposal_report">
              <el-input v-model="form.disposal_report" placeholder="请输入处置情况报告" type="textarea" :rows="2" />
            </el-form-item>
          </el-col>
          
          <!-- 第三列 -->
          <el-col :span="6">
            <el-divider content-position="left">个人信息（续）</el-divider>
            <el-form-item label="入党时间" prop="party_join_date">
              <el-date-picker v-model="form.party_join_date" type="date" placeholder="选择入党时间" />
            </el-form-item>
            <el-form-item label="干部管理权限" prop="cadre_management_authority">
              <el-input v-model="form.cadre_management_authority" placeholder="请输入干部管理权限" />
            </el-form-item>
            <el-form-item label="中管干部二级" prop="central_managed_cadre_level2">
              <el-input v-model="form.central_managed_cadre_level2" placeholder="请输入中管干部二级信息" />
            </el-form-item>
            <el-form-item label="影响期限结束时间" prop="impact_end_date">
              <el-date-picker v-model="form.impact_end_date" type="date" placeholder="请选择影响期限结束时间" />
            </el-form-item>

            <el-divider content-position="left">时间信息</el-divider>
            <el-form-item label="受理时间" prop="accept_time">
              <el-date-picker v-model="form.accept_time" type="date" placeholder="选择受理时间" />
            </el-form-item>
            <el-form-item label="受理统计时间" prop="accept_stat_time">
              <el-date-picker v-model="form.accept_stat_time" type="date" placeholder="选择受理统计时间" />
            </el-form-item>
            <el-form-item label="办结时间" prop="closing_time">
              <el-date-picker v-model="form.closing_time" type="date" placeholder="选择办结时间" />
            </el-form-item>
            <el-form-item label="办结统计时间" prop="closing_stat_time">
              <el-date-picker v-model="form.closing_stat_time" type="date" placeholder="选择办结统计时间" />
            </el-form-item>
            <el-form-item label="违纪违法行为发生时间" prop="violation_occurrence_time">
              <el-date-picker v-model="form.violation_occurrence_time" type="date" placeholder="选择发生时间" />
            </el-form-item>
            <el-form-item label="办理时间" prop="handling_time">
              <el-date-picker v-model="form.handling_time" type="date" placeholder="选择办理时间" />
            </el-form-item>
            <el-form-item label="办理统计时间" prop="handling_stat_time">
              <el-date-picker v-model="form.handling_stat_time" type="date" placeholder="选择办理统计时间" />
            </el-form-item>
          

            <el-divider content-position="left">线索来源</el-divider>
            <el-form-item label="线索来源" prop="clue_source">
              <el-input v-model="form.clue_source" placeholder="请输入线索来源" />
            </el-form-item>
            <el-form-item label="巡视巡察中发现二级分类" prop="inspection_found_level2">
              <el-input v-model="form.inspection_found_level2" placeholder="请输入二级分类" />
            </el-form-item>
            <el-form-item label="上级交办转办二级分类" prop="superior_assigned_level2">
              <el-input v-model="form.superior_assigned_level2" placeholder="请输入二级分类" />
            </el-form-item>
          </el-col>
          
          <!-- 第四列 -->
          <el-col :span="6">
            <el-divider content-position="left">办理结果及身份分类</el-divider>
            <el-form-item label="办理结果" prop="handling_result">
              <el-input v-model="form.handling_result" placeholder="请输入办理结果" />
            </el-form-item>
            <el-form-item label="是否党员" prop="is_party_member">
              <el-select v-model="form.is_party_member" placeholder="请选择">
                <el-option label="是" value="是" />
                <el-option label="否" value="否" />
              </el-select>
            </el-form-item>
            <el-form-item label="监察对象二级分类" prop="supervision_object_level2">
              <el-input v-model="form.supervision_object_level2" placeholder="请输入二级分类" />
            </el-form-item>
            <el-form-item label="非党员非监察对象二级分类" prop="non_party_non_supervision_level2">
              <el-input v-model="form.non_party_non_supervision_level2" placeholder="请输入二级分类" />
            </el-form-item>
            <el-form-item label="是否非党员非监察对象" prop="is_non_party_non_supervision">
              <el-select v-model="form.is_non_party_non_supervision" placeholder="请选择">
                <el-option label="是" value="是" />
                <el-option label="否" value="否" />
              </el-select>
            </el-form-item>
            
            <el-divider content-position="left">行为分类</el-divider>
            <el-form-item label="违纪行为" prop="disciplinary_violation">
              <el-input v-model="form.disciplinary_violation" placeholder="请输入违纪行为" />
            </el-form-item>
            <el-form-item label="职务违法犯罪行为" prop="duty_illegal_crime">
              <el-input v-model="form.duty_illegal_crime" placeholder="请输入职务违法犯罪行为" />
            </el-form-item>
            <el-form-item label="其他违法犯罪行为" prop="other_illegal_crime">
              <el-input v-model="form.other_illegal_crime" placeholder="请输入其他违法犯罪行为" />
            </el-form-item>

            <el-divider content-position="left">组织措施</el-divider>
            <el-form-item label="组织措施" prop="organizational_measures">
              <el-input v-model="form.organizational_measures" placeholder="请输入组织措施" />
            </el-form-item>
            <el-form-item label="组织措施统计时间" prop="organizational_measures_stat_time">
              <el-date-picker v-model="form.organizational_measures_stat_time" type="date" placeholder="选择统计时间" />
            </el-form-item>
            <el-form-item label="是否主动投案" prop="is_voluntary_surrender">
              <el-select v-model="form.is_voluntary_surrender" placeholder="请选择">
                <el-option label="是" value="是" />
                <el-option label="否" value="否" />
              </el-select>
            </el-form-item>
            <el-form-item label="是否属于向上级报告范围" prop="is_report_to_superior">
              <el-select v-model="form.is_report_to_superior" placeholder="请选择">
                <el-option label="是" value="是" />
                <el-option label="否" value="否" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        
        <!-- 处置方式（保留两条） -->
        <el-divider content-position="left">处置方式</el-divider>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="处置方式1批准时间" prop="disposal_method1_approval_time">
              <el-date-picker v-model="form.disposal_method1_approval_time" type="date" placeholder="选择批准时间" />
            </el-form-item>
            <el-form-item label="处置方式1统计时间" prop="disposal_method1_stat_time">
              <el-date-picker v-model="form.disposal_method1_stat_time" type="date" placeholder="选择统计时间" />
            </el-form-item>
            <el-form-item label="处置方式1一级" prop="disposal_method1_level1">
              <el-input v-model="form.disposal_method1_level1" placeholder="请输入一级分类" />
            </el-form-item>
            <el-form-item label="处置方式1二级" prop="disposal_method1_level2">
              <el-input v-model="form.disposal_method1_level2" placeholder="请输入二级分类" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="处置方式2批准时间" prop="disposal_method2_approval_time">
              <el-date-picker v-model="form.disposal_method2_approval_time" type="date" placeholder="选择批准时间" />
            </el-form-item>
            <el-form-item label="处置方式2统计时间" prop="disposal_method2_stat_time">
              <el-date-picker v-model="form.disposal_method2_stat_time" type="date" placeholder="选择统计时间" />
            </el-form-item>
            <el-form-item label="处置方式2一级" prop="disposal_method2_level1">
              <el-input v-model="form.disposal_method2_level1" placeholder="请输入一级分类" />
            </el-form-item>
            <el-form-item label="处置方式2二级" prop="disposal_method2_level2">
              <el-input v-model="form.disposal_method2_level2" placeholder="请输入二级分类" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <!-- 调查措施 -->
        <el-divider content-position="left">调查措施</el-divider>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="技术调查措施使用次数" prop="tech_investigation_measure_count">
              <el-input v-model="form.tech_investigation_measure_count" placeholder="请输入次数" type="number" />
            </el-form-item>
            <el-form-item label="限制出境措施使用次数" prop="exit_restriction_measure_count">
              <el-input v-model="form.exit_restriction_measure_count" placeholder="请输入次数" type="number" />
            </el-form-item>
            <el-form-item label="技术调查措施文书编号" prop="tech_investigation_doc_number">
              <el-input v-model="form.tech_investigation_doc_number" placeholder="请输入文书编号" />
            </el-form-item>
            <el-form-item label="限制出境措施文书编号" prop="exit_restriction_doc_number">
              <el-input v-model="form.exit_restriction_doc_number" placeholder="请输入文书编号" />
            </el-form-item>
            <el-form-item label="使用措施统计时间" prop="measure_stat_time">
              <el-date-picker v-model="form.measure_stat_time" type="date" placeholder="选择统计时间" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="转入办理环节" prop="transfer_to_handling">
              <el-select v-model="form.transfer_to_handling" placeholder="请选择">
                <el-option label="是" value="是" />
                <el-option label="否" value="否" />
              </el-select>
            </el-form-item>
            <el-form-item label="移交其他部门办理-部门名称" prop="transfer_department_name">
              <el-input v-model="form.transfer_department_name" placeholder="请输入部门名称" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <!-- 纪检监察建议（保留两条） -->
        <el-divider content-position="left">纪检监察建议</el-divider>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="提出建议的纪检监察机构名称1" prop="suggesting_agency1">
              <el-input v-model="form.suggesting_agency1" placeholder="请输入机构名称" />
            </el-form-item>
            <el-form-item label="被建议的单位（组织）名称1" prop="suggested_unit1">
              <el-input v-model="form.suggested_unit1" placeholder="请输入单位名称" />
            </el-form-item>
            <el-form-item label="建议类型1" prop="suggestion_type1">
              <el-input v-model="form.suggestion_type1" placeholder="请输入建议类型" />
            </el-form-item>
            <el-form-item label="建议文书内容1" prop="suggestion_content1">
              <el-input v-model="form.suggestion_content1" placeholder="请输入建议内容" type="textarea" :rows="2" />
            </el-form-item>
            <el-form-item label="提出建议时间1" prop="suggestion_time1">
              <el-date-picker v-model="form.suggestion_time1" type="date" placeholder="选择建议时间" />
            </el-form-item>
            <el-form-item label="提出建议统计时间1" prop="suggestion_stat_time1">
              <el-date-picker v-model="form.suggestion_stat_time1" type="date" placeholder="选择统计时间" />
            </el-form-item>
          </el-col>
          
          <el-col :span="12">
            <el-form-item label="提出建议的纪检监察机构名称2" prop="suggesting_agency2">
              <el-input v-model="form.suggesting_agency2" placeholder="请输入机构名称" />
            </el-form-item>
            <el-form-item label="被建议的单位（组织）名称2" prop="suggested_unit2">
              <el-input v-model="form.suggested_unit2" placeholder="请输入单位名称" />
            </el-form-item>
            <el-form-item label="建议类型2" prop="suggestion_type2">
              <el-input v-model="form.suggestion_type2" placeholder="请输入建议类型" />
            </el-form-item>
            <el-form-item label="建议文书内容2" prop="suggestion_content2">
              <el-input v-model="form.suggestion_content2" placeholder="请输入建议内容" type="textarea" :rows="2" />
            </el-form-item>
            <el-form-item label="提出建议时间2" prop="suggestion_time2">
              <el-date-picker v-model="form.suggestion_time2" type="date" placeholder="选择建议时间" />
            </el-form-item>
            <el-form-item label="提出建议统计时间2" prop="suggestion_stat_time2">
              <el-date-picker v-model="form.suggestion_stat_time2" type="date" placeholder="选择统计时间" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <!-- 涉外信息及其他 -->
        <el-divider content-position="left">涉外信息及其他</el-divider>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="涉外类别" prop="foreign_related_category">
              <el-input v-model="form.foreign_related_category" placeholder="请输入涉外类别" />
            </el-form-item>
            <el-form-item label="涉及国家（地区）" prop="involved_country">
              <el-input v-model="form.involved_country" placeholder="请输入涉及国家（地区）" />
            </el-form-item>
            <el-form-item label="涉外统计时间" prop="foreign_related_stat_time">
              <el-date-picker v-model="form.foreign_related_stat_time" type="date" placeholder="选择统计时间" />
            </el-form-item>
            <el-form-item label="涉外信息摘要" prop="foreign_related_summary">
              <el-input v-model="form.foreign_related_summary" placeholder="请输入涉外信息摘要" type="textarea" :rows="2" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="四种形态情形" prop="four_forms_situation">
              <el-input v-model="form.four_forms_situation" placeholder="请输入四种形态情形" />
            </el-form-item>
            <el-form-item label="四种形态统计时间" prop="four_forms_stat_time">
              <el-date-picker v-model="form.four_forms_stat_time" type="date" placeholder="选择统计时间" />
            </el-form-item>
            <el-form-item label="备注" prop="remarks">
              <el-input v-model="form.remarks" placeholder="请输入备注" type="textarea" :rows="2" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">保存</el-button>
      </template>
    </el-dialog>

        <!-- 导入Excel -->
    <el-dialog v-model="importDialogVisible" title="导入问题线索情况" width="40%">
          <el-upload
              class="upload-excel"
              action="#"
              :file-list="fileList"
              :auto-upload="false"
              :on-change="handleFileChange"
              accept=".xlsx,.xls"
              drag
                >
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">将Excel文件拖到此处，或<em>点击上传</em></div>
            <div class="el-upload__tip" slot="tip">仅支持.xlsx格式文件，需与模板字段一致</div>
             <div class="el-upload__tip" style="color: orangered;" slot="tip">（注意:请把Excel中的数字单元格设置为文本格式）</div>
          </el-upload>
          <template #footer>
            <el-button @click="importDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="submitImport">确认导入</el-button>
          </template>
    </el-dialog>

  </div>
</template>

<script setup>
import { Delete, Edit } from '@element-plus/icons-vue';
import TopNav from './navmenu.vue'
import { onMounted, ref } from 'vue'
import { ElMessage, ElMessageBox,ElLoading } from 'element-plus'
import dbClient from '../../utils/database.js'
import * as XLSX from 'xlsx';

// 新增导入相关响应式数据
const importDialogVisible = ref(false);
const fileList = ref([]);
let selectedFile = null;

// 字段映射：Excel列名 -> 数据库表字段名
const fieldMap = {
  // 基本信息
  '主件标识': 'main_mark',
  '是否单位': 'is_unit',
  '填报单位名称': 'report_unit_name',
  '填报单位代码': 'report_unit_code',
  '被反映人': 'reflected_person',
  '工作单位及职务': 'work_unit_and_position',
  '职级': 'rank',
  '办理机关': 'handling_agency',
  '主要问题线索': 'main_problem_clue',
  '信访编码': 'petition_code',
  
  // 受理信息
  '受理线索编码': 'accept_clue_code',
  '受理人员编码': 'accept_person_code',
  '处置线索编码': 'disposal_clue_code',
  '处置人员编码': 'disposal_person_code',
  
  // 对象信息
  '是否国家监察对象': 'is_national_supervision_object',
  '挽回经济损失（万元）': 'recover_economic_loss',
  '收缴金额（万元）': 'recovery_amount',
  '没收金额': 'confiscation_amount',
  '责令退赔金额': 'order_refund_amount',
  '登记上交金额': 'register_submit_amount',
  '追缴失职渎职滥用职权造成的损失金额': 'recover_loss_due_to_misconduct',
  '备注': 'remarks',
  
  // 个人信息
  '民族': 'ethnicity',
  '出生年月': 'birth_date',
  '人大代表': 'npc_member',
  '政协委员': 'cppcc_member',
  '是否纪检监察干部': 'is_discipline_inspection_official',
  '处置情况报告': 'disposal_report',
  '入党时间': 'party_join_date',
  '干部管理权限': 'cadre_management_authority',
  '中管干部二级': 'central_managed_cadre_level2',
  '影响期限结束日期': 'impact_end_date',
  
  // 时间信息
  '受理时间': 'accept_time',
  '受理统计时间': 'accept_stat_time',
  '办结时间': 'closing_time',
  '办结统计时间': 'closing_stat_time',
  '办理时间': 'handling_time',
  '办理统计时间': 'handling_stat_time',
  '违纪违法行为发生时间': 'violation_occurrence_time',
  '备注统计时间': 'remarks_stat_time',
  
  // 处置方式1-8
  '处置方式1批准时间': 'disposal_method1_approval_time',
  '处置方式1统计时间': 'disposal_method1_stat_time',
  '处置方式1一级': 'disposal_method1_level1',
  '处置方式1二级': 'disposal_method1_level2',
  '处置方式2批准时间': 'disposal_method2_approval_time',
  '处置方式2统计时间': 'disposal_method2_stat_time',
  '处置方式2一级': 'disposal_method2_level1',
  '处置方式2二级': 'disposal_method2_level2',
  '处置方式3批准时间': 'disposal_method3_approval_time',
  '处置方式3统计时间': 'disposal_method3_stat_time',
  '处置方式3一级': 'disposal_method3_level1',
  '处置方式3二级': 'disposal_method3_level2',
  '处置方式4批准时间': 'disposal_method4_approval_time',
  '处置方式4统计时间': 'disposal_method4_stat_time',
  '处置方式4一级': 'disposal_method4_level1',
  '处置方式4二级': 'disposal_method4_level2',
  '处置方式5批准时间': 'disposal_method5_approval_time',
  '处置方式5统计时间': 'disposal_method5_stat_time',
  '处置方式5一级': 'disposal_method5_level1',
  '处置方式5二级': 'disposal_method5_level2',
  '处置方式6批准时间': 'disposal_method6_approval_time',
  '处置方式6统计时间': 'disposal_method6_stat_time',
  '处置方式6一级': 'disposal_method6_level1',
  '处置方式6二级': 'disposal_method6_level2',
  '处置方式7批准时间': 'disposal_method7_approval_time',
  '处置方式7统计时间': 'disposal_method7_stat_time',
  '处置方式7一级': 'disposal_method7_level1',
  '处置方式7二级': 'disposal_method7_level2',
  '处置方式8批准时间': 'disposal_method8_approval_time',
  '处置方式8统计时间': 'disposal_method8_stat_time',
  '处置方式8一级': 'disposal_method8_level1',
  '处置方式8二级': 'disposal_method8_level2',
  
  // 线索来源相关
  '线索来源': 'clue_source',
  '巡视巡察中发现二级分类': 'inspection_found_level2',
  '上级交办转办二级分类': 'superior_assigned_level2',
  '是否与本人核实': 'is_verified_with_person',
  '是否主动交代问题': 'is_voluntary_confession',
  '纪检监察机关是否要求就谈话函询事项在民主（组织）生活会上作具体说明': 'is_explained_in_meeting',
  
  // 办理结果及身份分类
  '办理结果': 'handling_result',
  '是否党员': 'is_party_member',
  '监察对象二级分类': 'supervision_object_level2',
  '是否非党员非监察对象': 'is_non_party_non_supervision',
  '非党员非监察对象二级分类': 'non_party_non_supervision_level2',
  
  // 行为分类
  '违纪行为': 'disciplinary_violation',
  '职务违法犯罪行为': 'duty_illegal_crime',
  '其他违法犯罪行为': 'other_illegal_crime',
  
  // 组织措施
  '组织措施': 'organizational_measures',
  '组织措施统计时间': 'organizational_measures_stat_time',
  '是否主动投案': 'is_voluntary_surrender',
  '是否属于向上级纪委监委报告范围': 'is_report_to_superior',
  
  // 调查措施
  '技术调查措施使用次数': 'tech_investigation_measure_count',
  '限制出境措施使用次数': 'exit_restriction_measure_count',
  '技术调查措施的措施文书编号': 'tech_investigation_doc_number',
  '限制出境措施的措施文书编号': 'exit_restriction_doc_number',
  '使用措施统计时间': 'measure_stat_time',
  
  // 办理环节
  '转入办理环节': 'transfer_to_handling',
  '移交其他部门办理-部门名称': 'transfer_department_name',
  
  // 纪检监察建议1-8
  '提出建议的纪检监察机构名称1': 'suggesting_agency1',
  '被建议的单位（组织）名称1': 'suggested_unit1',
  '建议类型1': 'suggestion_type1',
  '建议文书内容1': 'suggestion_content1',
  '提出建议时间1': 'suggestion_time1',
  '提出建议统计时间1': 'suggestion_stat_time1',
  '提出建议的纪检监察机构名称2': 'suggesting_agency2',
  '被建议的单位（组织）名称2': 'suggested_unit2',
  '建议类型2': 'suggestion_type2',
  '建议文书内容2': 'suggestion_content2',
  '提出建议时间2': 'suggestion_time2',
  '提出建议统计时间2': 'suggestion_stat_time2',
  '提出建议的纪检监察机构名称3': 'suggesting_agency3',
  '被建议的单位（组织）名称3': 'suggested_unit3',
  '建议类型3': 'suggestion_type3',
  '建议文书内容3': 'suggestion_content3',
  '提出建议时间3': 'suggestion_time3',
  '提出建议统计时间3': 'suggestion_stat_time3',
  '提出建议的纪检监察机构名称4': 'suggesting_agency4',
  '被建议的单位（组织）名称4': 'suggested_unit4',
  '建议类型4': 'suggestion_type4',
  '建议文书内容4': 'suggestion_content4',
  '提出建议时间4': 'suggestion_time4',
  '提出建议统计时间4': 'suggestion_stat_time4',
  '提出建议的纪检监察机构名称5': 'suggesting_agency5',
  '被建议的单位（组织）名称5': 'suggested_unit5',
  '建议类型5': 'suggestion_type5',
  '建议文书内容5': 'suggestion_content5',
  '提出建议时间5': 'suggestion_time5',
  '提出建议统计时间5': 'suggestion_stat_time5',
  '提出建议的纪检监察机构名称6': 'suggesting_agency6',
  '被建议的单位（组织）名称6': 'suggested_unit6',
  '建议类型6': 'suggestion_type6',
  '建议文书内容6': 'suggestion_content6',
  '提出建议时间6': 'suggestion_time6',
  '提出建议统计时间6': 'suggestion_stat_time6',
  '提出建议的纪检监察机构名称7': 'suggesting_agency7',
  '被建议的单位（组织）名称7': 'suggested_unit7',
  '建议类型7': 'suggestion_type7',
  '建议文书内容7': 'suggestion_content7',
  '提出建议时间7': 'suggestion_time7',
  '提出建议统计时间7': 'suggestion_stat_time7',
  '提出建议的纪检监察机构名称8': 'suggesting_agency8',
  '被建议的单位（组织）名称8': 'suggested_unit8',
  '建议类型8': 'suggestion_type8',
  '建议文书内容8': 'suggestion_content8',
  '提出建议时间8': 'suggestion_time8',
  '提出建议统计时间8': 'suggestion_stat_time8',
  
  // 涉外信息
  '涉外类别': 'foreign_related_category',
  '涉及国家（地区）': 'involved_country',
  '涉外统计时间': 'foreign_related_stat_time',
  '涉外信息摘要': 'foreign_related_summary',
  
  // 四种形态
  '四种形态情形': 'four_forms_situation',
  '四种形态统计时间': 'four_forms_stat_time'
};

// 搜索相关响应式数据
const searchName = ref('');

// 分页相关响应式数据
const pagination = ref({
  currentPage: 1,
  pageSize: 10,
  total: 0
});

// 问题线索列表
const problemCluesList = ref([]);
const dialogVisible = ref(false);
const dialogTitle = ref('');
const form = ref({
  // 基本信息
  main_mark: '',
  is_unit: '',
  report_unit_name: '',
  report_unit_code: '',
  reflected_person: '',
  work_unit_and_position: '',
  rank: '',
  handling_agency: '',
  main_problem_clue: '',
  petition_code: '',
  
  // 受理信息
  accept_clue_code: '',
  accept_person_code: '',
  disposal_clue_code: '',
  disposal_person_code: '',
  
  // 对象信息
  is_national_supervision_object: '',
  recover_economic_loss: null,
  recovery_amount: null,
  confiscation_amount: null,
  order_refund_amount: null,
  register_submit_amount: null,
  recover_loss_due_to_misconduct: null,
  
  // 个人信息
  ethnicity: '',
  birth_date: '',
  npc_member: '',
  cppcc_member: '',
  is_discipline_inspection_official: '',
  disposal_report: '',
  party_join_date: '',
  cadre_management_authority: '',
  central_managed_cadre_level2: '',
  impact_end_date: '',
  
  // 时间信息
  accept_time: '',
  accept_stat_time: '',
  closing_time: '',
  closing_stat_time: '',
  handling_time: '',
  handling_stat_time: '',
  violation_occurrence_time: '',
  
  // 处置方式（保留两条）
  disposal_method1_approval_time: '',
  disposal_method1_stat_time: '',
  disposal_method1_level1: '',
  disposal_method1_level2: '',
  disposal_method2_approval_time: '',
  disposal_method2_stat_time: '',
  disposal_method2_level1: '',
  disposal_method2_level2: '',
  
  // 线索来源
  clue_source: '',
  inspection_found_level2: '',
  superior_assigned_level2: '',
  is_verified_with_person: '',
  is_voluntary_confession: '',
  is_explained_in_meeting: '',
  
  // 办理结果
  handling_result: '',
  
  // 身份分类
  is_party_member: '',
  supervision_object_level2: '',
  is_non_party_non_supervision: '',
  non_party_non_supervision_level2: '',
  
  // 行为分类
  disciplinary_violation: '',
  duty_illegal_crime: '',
  other_illegal_crime: '',
  
  // 组织措施
  organizational_measures: '',
  organizational_measures_stat_time: '',
  is_voluntary_surrender: '',
  is_report_to_superior: '',
  
  // 调查措施
  tech_investigation_measure_count: null,
  exit_restriction_measure_count: null,
  tech_investigation_doc_number: '',
  exit_restriction_doc_number: '',
  measure_stat_time: '',
  
  // 办理环节
  transfer_to_handling: '',
  transfer_department_name: '',
  
  // 违纪违法行为时间
  violation_occurrence_time: '',
  
  // 纪检监察建议（保留两条）
  suggesting_agency1: '',
  suggested_unit1: '',
  suggestion_type1: '',
  suggestion_content1: '',
  suggestion_time1: '',
  suggestion_stat_time1: '',
  suggesting_agency2: '',
  suggested_unit2: '',
  suggestion_type2: '',
  suggestion_content2: '',
  suggestion_time2: '',
  suggestion_stat_time2: '',
  
  // 涉外信息
  foreign_related_category: '',
  involved_country: '',
  foreign_related_stat_time: '',
  foreign_related_summary: '',
  
  // 四种形态
  four_forms_situation: '',
  four_forms_stat_time: '',
  
  // 备注
  remarks: ''
});
const formRef = ref(null);

const rules = {
  // 基本信息
  reflected_person: [
    { required: true, message: '请输入被反映人', trigger: 'blur' }
  ],
  report_unit_name: [
    { required: true, message: '请输入填报单位名称', trigger: 'blur' }
  ],
  work_unit_and_position: [
    { required: true, message: '请输入工作单位及职务', trigger: 'blur' }
  ],
  handling_agency: [
    { required: true, message: '请输入办理机关', trigger: 'blur' }
  ],
  accept_clue_code: [
    { required: true, message: '请输入受理线索编码', trigger: 'blur' }
  ],
  accept_person_code:[
    { required:true, message: '请输入受理人员编码', trigger: 'blur' }
  ],
  
  // 个人信息
  id_number: [
    { required: true, message: '请输入身份证号', trigger: 'blur' },
    { 
      pattern: /^[1-9]\d{5}(19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/, 
      message: '请输入正确的18位身份证号', 
      trigger: 'blur' 
    }
  ],
  
};

// 显示导入对话框
const showImportDialog = () => {
  importDialogVisible.value = true;
  fileList.value = [];
  selectedFile = null;
};

// 选择文件变化时触发
const handleFileChange = (uploadFile) => {
  fileList.value = [uploadFile];
  selectedFile = uploadFile.raw;
};

// 页面加载时获取数据
onMounted(() => {
  getProblemCluesList();
});

const handleSearch = () => {
  pagination.value.currentPage = 1; // 搜索时重置到第一页
  getProblemCluesList();
};

// 获取问题线索列表
const getProblemCluesList = async () => {
  try {
    let query = 'SELECT * FROM problem_clues_situation';
    let countQuery = 'SELECT COUNT(*) as total FROM problem_clues_situation';
    let params = [];
    
    if (searchName.value && searchName.value.trim()) {
      // 使用模糊查询，匹配被反映人中包含搜索词的记录
      const whereClause = ' WHERE reflected_person LIKE ?'; // 添加空格修复语法错误
      query += whereClause;
      countQuery += whereClause;
      params.push(`%${searchName.value.trim()}%`);
    } 

    //添加排序
    query += ' ORDER BY id DESC';
    
    // 添加分页
    const offset = (pagination.value.currentPage - 1) * pagination.value.pageSize;
    query += ` LIMIT ${pagination.value.pageSize} OFFSET ${offset}`;
    
    // 获取总数
    const countResult = await dbClient.query(countQuery, params);
    pagination.value.total = countResult[0].total;
    
    // 获取分页数据
    const data = await dbClient.query(query, params);
    problemCluesList.value = data;
    } catch (error) {
      console.error('获取问题线索列表失败:', {
        error,
        query: query,
        params: params,
        countQuery: countQuery
      });
      ElMessage.error(`获取问题线索列表失败: ${error.message || '未知错误'}`);
    }
};

// 处理分页大小变化
const handleSizeChange = (newSize) => {
  pagination.value.pageSize = newSize;
  pagination.value.currentPage = 1; // 页数大小改变时重置到第一页
  getProblemCluesList();
};

// 处理当前页变化
const handleCurrentChange = (newPage) => {
  pagination.value.currentPage = newPage;
  getProblemCluesList();
};

// 显示新增对话框
const showAddDialog = () => {
  dialogTitle.value = '新增问题线索';
  form.value = {
    // 基本信息
    main_mark: '',
    is_unit: '',
    report_unit_name: '',
    report_unit_code: '',
    reflected_person: '',
    work_unit_and_position: '',
    rank: '',
    handling_agency: '',
    main_problem_clue: '',
    petition_code: '',
    
    // 受理信息
    accept_clue_code: '',
    accept_person_code: '',
    disposal_clue_code: '',
    disposal_person_code: '',
    
    // 对象信息
    is_national_supervision_object: '',
    recover_economic_loss: null,
    recovery_amount: null,
    confiscation_amount: null,
    order_refund_amount: null,
    register_submit_amount: null,
    recover_loss_due_to_misconduct: null,
    
    // 个人信息
    ethnicity: '',
    birth_date: '',
    npc_member: '',
    cppcc_member: '',
    is_discipline_inspection_official: '',
    disposal_report: '',
    party_join_date: '',
    cadre_management_authority: '',
    central_managed_cadre_level2: '',
    impact_end_date: '',
    
    // 时间信息
    accept_time: '',
    accept_stat_time: '',
    closing_time: '',
    closing_stat_time: '',
    handling_time: '',
    handling_stat_time: '',
    violation_occurrence_time: '',
    
    // 处置方式（保留两条）
    disposal_method1_approval_time: '',
    disposal_method1_stat_time: '',
    disposal_method1_level1: '',
    disposal_method1_level2: '',
    disposal_method2_approval_time: '',
    disposal_method2_stat_time: '',
    disposal_method2_level1: '',
    disposal_method2_level2: '',
    
    // 线索来源
    clue_source: '',
    inspection_found_level2: '',
    superior_assigned_level2: '',
    is_verified_with_person: '',
    is_voluntary_confession: '',
    is_explained_in_meeting: '',
    
    // 办理结果
    handling_result: '',
    
    // 身份分类
    is_party_member: '',
    supervision_object_level2: '',
    is_non_party_non_supervision: '',
    non_party_non_supervision_level2: '',
    
    // 行为分类
    disciplinary_violation: '',
    duty_illegal_crime: '',
    other_illegal_crime: '',
    
    // 组织措施
    organizational_measures: '',
    organizational_measures_stat_time: '',
    is_voluntary_surrender: '',
    is_report_to_superior: '',
    
    // 调查措施
    tech_investigation_measure_count: null,
    exit_restriction_measure_count: null,
    tech_investigation_doc_number: '',
    exit_restriction_doc_number: '',
    measure_stat_time: '',
    
    // 办理环节
    transfer_to_handling: '',
    transfer_department_name: '',
    
    // 违纪违法行为时间
    violation_occurrence_time: '',
    
    // 纪检监察建议（保留两条）
    suggesting_agency1: '',
    suggested_unit1: '',
    suggestion_type1: '',
    suggestion_content1: '',
    suggestion_time1: '',
    suggestion_stat_time1: '',
    suggesting_agency2: '',
    suggested_unit2: '',
    suggestion_type2: '',
    suggestion_content2: '',
    suggestion_time2: '',
    suggestion_stat_time2: '',
    
    // 涉外信息
    foreign_related_category: '',
    involved_country: '',
    foreign_related_stat_time: '',
    foreign_related_summary: '',
    
    // 四种形态
    four_forms_situation: '',
    four_forms_stat_time: '',
    
    // 备注
    remarks: ''
  };
  dialogVisible.value = true;
};

// 显示编辑对话框
const handleEdit = (row) => {
  dialogTitle.value = '编辑问题线索';
  
  // 将字符串日期转换为 Date 对象
  const processedData = { ...row };
  const dateFields = ['impact_end_date','accept_time', 'accept_stat_time', 'handling_time', 'handling_stat_time'];
  
  dateFields.forEach(field => {
    if (processedData[field]) {
      processedData[field] = new Date(processedData[field]);
    }
  });
  
  form.value = processedData;
  dialogVisible.value = true;
};

// 删除问题线索
const handleDelete = async (id) => {
  try {
    await ElMessageBox.confirm('是否要删除当前行数据？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });
    
    await dbClient.delete('DELETE FROM problem_clues_situation WHERE id = ?', [id]);
    ElMessage.success('删除成功');
    getProblemCluesList(searchName.value);
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error);
      ElMessage.error('删除失败: ' + error.message);
    }
  }
};

// 提交表单
const submitForm = async () => {
  try {
    // 先进行表单验证
    await formRef.value.validate();
  } catch (error) {
    // 表单验证失败，直接返回，不执行后续操作
    console.log('表单验证失败:', error);
    return;
  }
  
  // 验证受理人员编码是否存在于领导人员基本情况表中
  const idNumber = form.value.accept_person_code;
  try {
    const result = await dbClient.query(
      'SELECT id FROM leader_personnel_infro WHERE personnel_code = ?',
      [idNumber]
    );
    
    if (result.length === 0) {
      ElMessage.warning('此领导不存在于领导人员基本情况表中，请验证受理人员编码是否正确');
      return; // 验证失败，不提交
    }
  } catch (error) {
    console.error('验证受理人员编码失败:', error);
    ElMessage.error('验证领导人员信息时发生错误');
    return;
  }

  // 验证受理线索编码是否已存在
  const acceptClueCode = form.value.accept_clue_code;
  const existingClue = await dbClient.query(
    'SELECT id FROM problem_clues_situation WHERE accept_clue_code = ?',
    [acceptClueCode]
  );

  // 如果是编辑模式，排除当前记录
  if (form.value.id) {
    const existingRecord = existingClue.find(item => item.id !== form.value.id);
    if (existingRecord) {
      ElMessage.warning('此受理线索编码重复，请修改');
      return; // 验证失败，不提交
    }
  } else {
    // 新增模式，直接检查是否存在
    if (existingClue.length > 0) {
      ElMessage.warning('此受理线索编码重复，请修改');
      return; // 验证失败，不提交
    }
  }
  
  // 处理表单数据：日期格式转换 + 提取字段/值
  const formData = { ...form.value };
  
  // 需要转换为字符串的日期字段
  const dateFields = [
    'impact_end_date',
    'accept_time', 'accept_stat_time', 
    'handling_time', 'handling_stat_time',
    'closing_time', 'closing_stat_time',
    'birth_date', 'party_join_date',
    'violation_occurrence_time',
    'disposal_method1_approval_time',
    'disposal_method1_stat_time',
    'disposal_method2_approval_time',
    'disposal_method2_stat_time',
    'suggestion_time1',
    'suggestion_stat_time1',
    'suggestion_time2',
    'suggestion_stat_time2',
    'organizational_measures_stat_time',
    'measure_stat_time',
    'foreign_related_stat_time',
    'four_forms_stat_time'
  ];

  // 转换日期为 YYYY-MM-DD 字符串（与cases.vue保持一致）
  dateFields.forEach(field => {
    // 确保字段存在并且是Date对象
    if (formData[field] && formData[field] instanceof Date && !isNaN(formData[field].getTime())) {
      // 格式化为YYYY-MM-DD
      const year = formData[field].getFullYear();
      const month = String(formData[field].getMonth() + 1).padStart(2, '0');
      const day = String(formData[field].getDate()).padStart(2, '0');
      formData[field] = `${year}-${month}-${day}`;
    }
  });

  // 自动获取字段名（排除空值可选，按需添加）
  const fields = Object.keys(formData).filter(key => key !== 'id'); // 新增/编辑都排除id（更新时单独传）
  const values = fields.map(key => formData[key]);

  try {
    if (formData.id) {
      // 编辑：更新数据 - 需要将id添加到values数组末尾
      const setClause = fields.map(field => `${field} = ?`).join(', ');
      const updateValues = [...values, formData.id]; // 添加id到values末尾
      await dbClient.update(
        `UPDATE problem_clues_situation SET ${setClause} WHERE id = ?`,
        updateValues
      );
      ElMessage.success('更新成功');
    } else {
      // 新增：插入数据
      const placeholders = fields.map(() => '?').join(',');
      await dbClient.insert(
        `INSERT INTO problem_clues_situation (${fields.join(', ')}) VALUES (${placeholders})`,
        values
      );
      ElMessage.success('新增成功');
    }

    dialogVisible.value = false;
    getProblemCluesList(searchName.value); // 重新加载列表，保持当前搜索状态
  } catch (error) {
    console.error('保存失败:', error);
    if (error.message.includes('can only bind numbers, strings')) {
      ElMessage.error('保存失败: 日期格式转换错误，请确保选择了有效的日期');
    } else {
      ElMessage.error('保存失败: ' + error.message);
    }
  }
};

// 提交导入数据
const submitImport = async () => {
  if (!selectedFile) {
    ElMessage.warning('请选择要导入的Excel文件');
    return;
  }
  try {
    // 解析Excel文件
    const fileReader = new FileReader();
    fileReader.readAsBinaryString(selectedFile);
    fileReader.onload = async (event) => {
      const workbook = XLSX.read(event.target.result, { type: 'binary' });
      const worksheet = workbook.Sheets[workbook.SheetNames[0]];
      const excelData = XLSX.utils.sheet_to_json(worksheet);
      
      if (excelData.length === 0) {
        ElMessage.warning('Excel文件中无数据');
        return;
      }

      // 定义需处理的日期字段和数字字段（严格对应auth.js表字段）
      const dateFields = [
        'impact_end_date',
        'birth_date', 'party_join_date', 'accept_time', 'accept_stat_time',
        'closing_time', 'closing_stat_time', 'handling_time', 'handling_stat_time',
        'violation_occurrence_time', 'remarks_stat_time', 'foreign_related_stat_time',
        'four_forms_stat_time', 'measure_stat_time', 'organizational_measures_stat_time',
        'disposal_method1_approval_time', 'disposal_method1_stat_time',
        'disposal_method2_approval_time', 'disposal_method2_stat_time',
        'disposal_method3_approval_time', 'disposal_method3_stat_time',
        'disposal_method4_approval_time', 'disposal_method4_stat_time',
        'disposal_method5_approval_time', 'disposal_method5_stat_time',
        'disposal_method6_approval_time', 'disposal_method6_stat_time',
        'disposal_method7_approval_time', 'disposal_method7_stat_time',
        'disposal_method8_approval_time', 'disposal_method8_stat_time',
        'suggestion_time1', 'suggestion_stat_time1', 'suggestion_time2',
        'suggestion_stat_time2', 'suggestion_time3', 'suggestion_stat_time3',
        'suggestion_time4', 'suggestion_stat_time4', 'suggestion_time5',
        'suggestion_stat_time5', 'suggestion_time6', 'suggestion_stat_time6',
        'suggestion_time7', 'suggestion_stat_time7', 'suggestion_time8',
        'suggestion_stat_time8'
      ];
      const numberFields = [
        'recover_economic_loss', 'recovery_amount', 'confiscation_amount',
        'order_refund_amount', 'register_submit_amount', 'recover_loss_due_to_misconduct',
        'tech_investigation_measure_count', 'exit_restriction_measure_count'
      ];

      // 数据处理：字段映射 + 格式转换
      const importData = [];
      for (const item of excelData) {
        const formattedItem = {};
        let isItemValid = true;

        // 1. 字段映射（Excel列名 → 数据库表字段）
        Object.keys(fieldMap).forEach(excelField => {
          const dbField = fieldMap[excelField];
          formattedItem[dbField] = item[excelField] || '';
        });

        // 2. 日期格式处理（兼容Excel数字/文本格式，统一转为YYYY-MM-DD）
        dateFields.forEach(dbField => {
          const excelValue = formattedItem[dbField];
          if (!excelValue) return;

          try {
            let dateObj;
            if (typeof excelValue === 'number') {
              // 处理Excel数字格式日期（如44927 → 2023-01-01）
              const dateCode = XLSX.SSF.parse_date_code(excelValue, { date1904: false });
              dateObj = new Date(dateCode.y, dateCode.m - 1, dateCode.d);
            } else if (typeof excelValue === 'string') {
              // 处理文本格式日期（如"2023-10-01"、"5/31/25"）
              dateObj = new Date(excelValue);
            } else {
              isItemValid = false;
              ElMessage.warning(`数据【${formattedItem.reflected_person || '未知'}】的${dbField}字段格式无效`);
              return;
            }

            if (isNaN(dateObj.getTime())) {
              isItemValid = false;
              ElMessage.warning(`数据【${formattedItem.reflected_person || '未知'}】的${dbField}字段日期无效（${excelValue}）`);
              return;
            }

            formattedItem[dbField] = `${dateObj.getFullYear()}-${String(dateObj.getMonth() + 1).padStart(2, '0')}-${String(dateObj.getDate()).padStart(2, '0')}`;
          } catch (error) {
            isItemValid = false;
            ElMessage.warning(`数据【${formattedItem.reflected_person || '未知'}】的${dbField}字段解析失败：${error.message}`);
          }
        });

        // 3. 数字格式处理（空值转null，非负验证）
        numberFields.forEach(dbField => {
          const excelValue = formattedItem[dbField];
          if (excelValue === '' || excelValue === null || excelValue === undefined) {
            formattedItem[dbField] = null;
            return;
          }

          const numericValue = Number(excelValue);
          if (isNaN(numericValue) || numericValue < 0) {
            isItemValid = false;
            ElMessage.warning(`数据【${formattedItem.reflected_person || '未知'}】的${dbField}字段需为非负数字`);
          } else {
            formattedItem[dbField] = numericValue;
          }
        });

        // 在日期格式处理和数字格式处理之后，添加文本字段处理，2025.11.26
          const textFields = ['report_unit_code']; // 可以扩展其他需要强制转换为文本的字段
          textFields.forEach(dbField => {
              if (formattedItem[dbField] !== null && formattedItem[dbField] !== undefined) {
                formattedItem[dbField] = String(formattedItem[dbField]);
              }
            });

        // 保留有效数据
        if (isItemValid) {
          importData.push(formattedItem);
        }
      }

      // 4. 验证必填字段（对应auth.js表必填约束）
      const requiredFields = ['report_unit_name', 'reflected_person', 'work_unit_and_position', 'handling_agency', 'accept_clue_code', 'accept_person_code'];
      const validData = importData.filter(item => {
        const hasAllRequired = requiredFields.every(field => {
          const rawValue = item[field];
          const processedValue = rawValue === undefined || rawValue === null ? '' : String(rawValue).trim();
          return processedValue !== '';
        });

        if (!hasAllRequired) {
          const missingFields = requiredFields.filter(field => {
            const rawValue = item[field];
            const processedValue = rawValue === undefined || rawValue === null ? '' : String(rawValue).trim();
            return processedValue === '';
          });
          ElMessage.warning(`数据【${item.reflected_person || '未知人员'}】缺少必填字段：${missingFields.join('、')}，已过滤`);
        }
        return hasAllRequired;
      });

      const invalidCount = importData.length - validData.length;
      if (invalidCount > 0) {
        ElMessage.warning(`共${invalidCount}条数据无效（格式错误/缺少必填项），已过滤`);
      }
      if (validData.length === 0) {
        ElMessage.error('无有效数据可导入');
        return;
      }

      // 5. 额外验证（受理人员编码的存在性）
      const finalValidData = [];
      for (const item of validData) {
        item.accept_person_code = item.accept_person_code.toString().trim();
        // 验证受理人员编码(accept_person_code)是否存在于领导人员表（auth.js中leader_personnel_infro表的personnel_code字段）
        const acceptPersonCodeCheck = await dbClient.query(
          'SELECT id FROM leader_personnel_infro WHERE personnel_code = ?',
          [item.accept_person_code]
        );
        if (acceptPersonCodeCheck.length === 0) {
          ElMessage.warning(`数据【${item.reflected_person}】的受理人员编码不存在于领导人员表，已过滤`);
          continue;
        }

        // // 验证受理线索编码唯一性（auth.js中accept_clue_code为UNIQUE字段）
        // const clueCodeCheck = await dbClient.query(
        //   'SELECT id FROM problem_clues_situation WHERE accept_clue_code = ?',
        //   [item.accept_clue_code]
        // );
        // if (clueCodeCheck.length > 0) {
        //   ElMessage.warning(`数据【${item.reflected_person}】的受理线索编码已存在，已过滤`);
        //   continue;
        // }

        finalValidData.push(item);
      }

      if (finalValidData.length === 0) {
        ElMessage.error('无有效数据可导入（受理人员编码不存在）');
        return;
      }

      // 6. 批量导入数据库（适配auth.js表结构）
      try {
        const fields = Object.values(fieldMap);
        const placeholders = fields.map(() => '?').join(',');
        const values = finalValidData.map(item => fields.map(field => item[field]));

        await dbClient.batchInsert(
          `INSERT OR REPLACE INTO problem_clues_situation (${fields.join(', ')}) VALUES (${placeholders})`,
          values
        );

        ElMessage.success(`成功导入${finalValidData.length}条问题线索数据,(新增或更新)`);
        importDialogVisible.value = false;
        getProblemCluesList(searchName.value); // 重新加载列表
      } catch (dbError) {
        console.error('数据库导入失败:', dbError);
        ElMessage.error(`导入失败：${dbError.message}`);
      }
    };
  } catch (error) {
    console.error('导入失败:', error);
    ElMessage.error('导入失败: ' + error.message);
  }
};

// 导出数据到 Excel
const exportData = async () => {
  let loadingInstance = null;
  try {
    // 显示加载特效
    loadingInstance = ElLoading.service({
      lock: true,
      text: '正在导出数据，请稍候...',
      background: 'rgba(0, 0, 0, 0.7)'
    });
    
    // 构建查询条件（与搜索条件一致）
    let query = 'SELECT * FROM problem_clues_situation';
    let params = [];
    
    if (searchName.value && searchName.value.trim()) {
      query += ' WHERE reflected_person LIKE ?';
      params.push(`%${searchName.value.trim()}%`);
    }
    
    // 添加排序
    query += ' ORDER BY id DESC';
    
    // 获取所有符合条件的数据（不分页）
    const data = await dbClient.query(query, params);
    
    if (!data || data.length === 0) {
      ElMessage.warning('没有数据可导出');
      return;
    }
    
    // 创建工作簿
    const workbook = XLSX.utils.book_new();
    
    // 创建反向映射：数据库字段名 -> 中文名称
    const reverseFieldMap = {};
    Object.keys(fieldMap).forEach(chineseName => {
      const dbField = fieldMap[chineseName];
      reverseFieldMap[dbField] = chineseName;
    });
    
    // 定义需要排除的字段
    const excludedFields = ['id', 'created_at', 'updated_at', 'created_by', 'updated_by'];
    
    // 准备表头和数据 - 过滤掉不需要的字段
    const allFields = Object.keys(data[0]);
    const filteredFields = allFields.filter(field => !excludedFields.includes(field));
    
    const headers = filteredFields.map(field => reverseFieldMap[field] || field);
    const excelData = [
      headers, // 第一行是中文表头
      ...data.map(row => 
        filteredFields.map(field => {
          // 处理日期字段，确保格式正确
          const value = row[field];
          if (value && typeof value === 'string' && value.match(/^\d{4}-\d{2}-\d{2}/)) {
            return value; // 保持日期格式
          }
          return value || '';
        })
      )
    ];
    
    // 创建工作表
    const worksheet = XLSX.utils.aoa_to_sheet(excelData);
    
    // 设置列宽自适应
    const colWidths = headers.map(header => ({
      wch: Math.max(header.length, 10) // 最小宽度10，根据内容调整
    }));
    worksheet['!cols'] = colWidths;
    
    // 将工作表添加到工作簿
    XLSX.utils.book_append_sheet(workbook, worksheet, '问题线索情况');
    
    // 生成带时分秒的文件名
    const now = new Date();
    const dateStr = now.toISOString().slice(0, 10).replace(/-/g, '');
    const timeStr = now.toTimeString().slice(0, 8).replace(/:/g, '');
    const fileName = `问题线索情况_${dateStr}_${timeStr}.xlsx`;
    
    // 生成 Excel 文件并下载
    XLSX.writeFile(workbook, fileName);
    
    ElMessage.success(`成功导出 ${data.length} 条数据`);
    
  } catch (error) {
    console.error('导出失败:', error);
    ElMessage.error(`导出失败: ${error.message || '未知错误'}`);
  } finally {
    // 关闭加载特效
    if (loadingInstance) {
      loadingInstance.close();
    }
  }
};

</script>

<style scoped>
.page-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background: #f5f6f7;
}

.card-container {
  flex: 1;
  padding: 20px;
  box-sizing: border-box;
}

/* 卡片：占满容器高度 */
.full-height-card {
  height: 99%;
  display: flex;
  flex-direction: column;
  background: #f5f6f7; /* 浅灰色背景 */
  margin: 10px;
}

/* 头部区域 */
:deep(.el-card__header) {
  min-height: 60px;
  display: flex;
  align-items: center;
  padding: 0 20px;
  flex-shrink: 0;
  background: white;
}

/* 卡片主体内容区域：占据剩余空间 */
:deep(.el-card__body) {
  flex: 1;
  display: flex;
  flex-direction: column;
  padding: 0;
  background: #f5f6f7; /* 浅灰色背景 */
}

/* 表格容器：自适应高度 + 滚动机制 */
.table-wrapper {
  margin: 20px 20px;
  background: white; /* 表格区域白色背景 */
  border-radius: 4px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  max-height: calc(100vh - 300px); /* 计算可用高度（减去导航栏、卡片头和按钮栏的高度） */
  overflow-y: auto; /* 垂直滚动 */
}

/* 表格：自适应高度 */
.full-height-table {
  width: 100%;
}

/* 底部按钮区域 */
:deep(.el-card__footer) {
  min-height: 60px;
  display: flex;
  align-items: center;
  padding: 0 20px;
  border-top: 1px solid #eee;
  flex-shrink: 0;
  background: white;
}

/* 操作按钮区域样式 */
.action-bar {
  margin: 15px 15px 15px 15px;
  padding: 5px;
}

.button-group {
  display: flex;
  gap: 10px;
  justify-content: flex-end;
  align-items: center;
}

/* 输入框样式调整 */
:deep(.el-input__wrapper) {
  width: 100%;
}

/* 按钮样式优化 */
.action-bar .el-button {
  min-width: 100px;
  height: 40px;
  font-size: 16px;
  font-weight: 500;
}

/* 搜索框样式优化 */
.action-bar .el-input {
  margin-right: 10px;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .action-bar .el-row {
    flex-direction: column;
    gap: 15px;
  }
  
  .action-bar .el-col {
    width: 100%;
  }
  
  .button-group {
    justify-content: center;
  }
}

/* 卡片容器间距调整 */
.card-container {
  flex: 1;
  padding: 10px 20px 20px 20px;
  box-sizing: border-box;
}

/* 表格容器间距调整 */
.table-wrapper {
  margin: 10px 0;
}

/* 表头字体加粗样式 */
:deep(.el-table__header th .cell) {
  font-weight: bold;
  font-size: 18px;
  color: #1d1d1da9;
}

:deep(.el-table__body td .cell) {
  font-size: 18px;
}

/* 分页样式 */
.pagination-container {
  display: flex;
  justify-content: center;
  padding: 16px;
  background: white;
  border-top: 1px solid #ebeef5;
}

/* 分割线样式优化 */
:deep(.el-divider__text) {
  font-weight: bold;
  color: #409EFF;
}

/* 表单标签样式 */
:deep(.el-form-item__label) {
  font-weight: 500;
}

</style>